#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:

"""
@version: 1.0
@author: readerror
@contact: readerror@readerror.cn
@contact1: readerror000@gmail.com
@site: http://www.readerror.cn
@software: PyCharm
@file: utils.py
@time: 2017/3/30 17:55
"""


def get_resources_owner(client, resources, resources_type=None):
    accounts_uuid = set()
    # TODO map 占用内存注意
    resource_account_map = {}
    for r in client.query_account_resource_ref(
            {"conditions": [{"name": "resourceType", "value": resources_type, "op": "="}]} if resources_type else None):
        account_uuid = r.get('accountUuid')
        resource_account_map[r.get('resourceUuid')] = account_uuid
        accounts_uuid.add(account_uuid)

    account_name_map = {}
    for account in client.query_account(
            {"conditions": [{"name": "uuid", "value": ','.join(list(accounts_uuid)), "op": "in"}]}):
        account_name_map[account.get('uuid')] = account.get('name')

    for resource in resources:
        resource['owner_uuid'] = resource_account_map.get(resource.get('uuid'))
        resource['owner_username'] = account_name_map.get(resource_account_map.get(resource.get('uuid')))

    return resources


def from_nics_get_vms(client, nics_uuid):
    nic_vm_map = {}
    for nic in client.query_vm_nic({"fields": ["vmInstanceUuid", "uuid"],
                                    "conditions": [{"name": "uuid", "value": ','.join(list(nics_uuid)), "op": "in"}]}):
        nic_vm_map[nic.get('uuid')] = nic.get('vmInstanceUuid')
    return nic_vm_map
